package com.sunwoda.springbootredis.redislock;

import com.sunwoda.springbootredis.util.RedisBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * @program: springbootredis
 * @description: 分布式锁
 * @author: SGR
 * @create: 2021-09-14 08:58
 **/
@Slf4j
@Component
public class LockVersion1 {

    /**
     * 存在的问题，不一定能释放锁
     */

    private static final String PRODUCT_ID = "100001";

    public String deductStock(){
        RedisTemplate redisTemplate = RedisBean.redis;
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        Boolean result = redisTemplate.opsForValue().setIfAbsent(PRODUCT_ID, "lock");
        if (!result){
            return "error";
        }
        redisTemplate.opsForValue().set("stock",100);
        Object o = redisTemplate.opsForValue().get("stock");
        log.info("值"+o);
        int stock = (int) redisTemplate.opsForValue().get("stock");
        if (stock > 0){
            log.info("减前的数值"+stock);
            stock -= 1;
            redisTemplate.opsForValue().set("stock",stock);
            log.info("减后的数值"+stock);
        }else {
            log.info("库存不足");
        }

        Boolean delete = false;
        do {
             delete = redisTemplate.delete(PRODUCT_ID);
        }while (!delete);

        return "success";
    }
}
